package com.example.msgsendmail;

import android.content.ContentResolver;
import android.content.Context;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import java.util.Date;
import java.util.concurrent.atomic.AtomicBoolean;

public class SmsContentObserver extends ContentObserver {
    private static final String TAG = "SmsContentObserver";
    private final Context context;
    private final ContentResolver contentResolver;
    private long lastSmsId = -1;
    private long lastCheckTime = 0;
    // 2025-06-03 修改：增加初始延迟时间和重试机制
    private static final int INITIAL_DELAY = 1500; // 初始延迟1.5秒
    private static final int MAX_RETRIES = 3; // 最大重试次数
    private static final int RETRY_DELAY = 1000; // 每次重试延迟1秒
    // 2025-06-03 添加：防止重复处理
    private AtomicBoolean isProcessing = new AtomicBoolean(false);

    public SmsContentObserver(Context context, Handler handler) {
        super(handler);
        this.context = context;
        this.contentResolver = context.getContentResolver();
        // 初始化时获取最新短信ID
        getLatestSmsId();
    }

    @Override
    public void onChange(boolean selfChange) {
        onChange(selfChange, null);
    }

    @Override
    public void onChange(boolean selfChange, Uri uri) {
        Log.d(TAG, "短信数据库变化: " + (uri != null ? uri.toString() : "null"));

        // 防止短时间内多次触发
        long currentTime = System.currentTimeMillis();
        if (currentTime - lastCheckTime < 500) {
            return;
        }
        lastCheckTime = currentTime;

        // 2025-06-03 修改：避免重复处理
        if (isProcessing.getAndSet(true)) {
            Log.d(TAG, "已有正在处理的短信，跳过本次触发");
            return;
        }

        // 2025-06-03 修改：使用重试机制替代固定延迟
        checkForNewSmsWithRetry(0);
    }

    // 2025-06-03 添加：带重试机制的短信检查方法
    private void checkForNewSmsWithRetry(int retryCount) {
        try {
            // 2025-06-03 修改：只查询inbox URI，避免重复数据
            Uri mainUri = Uri.parse("content://sms/inbox");
            boolean hasNewSms = checkSmsFromUri(mainUri);

            if (!hasNewSms && retryCount < MAX_RETRIES) {
                // 如果没有找到新短信且未达到最大重试次数，则重试
                Log.d(TAG, "未找到新短信，尝试重试 " + (retryCount + 1) + "/" + MAX_RETRIES);
                new Handler(Looper.getMainLooper()).postDelayed(() -> {
                    checkForNewSmsWithRetry(retryCount + 1);
                }, RETRY_DELAY);
                return;
            }
        } catch (Exception e) {
            Log.e(TAG, "检查新短信时出错: " + e.getMessage(), e);
        } finally {
            // 处理完成，允许下一次处理
            isProcessing.set(false);
        }
    }

    private boolean checkSmsFromUri(Uri uri) {
        boolean hasNewSms = false;
        Cursor cursor = null;

        try {
            // 2025-06-03 修改：添加read字段和筛选条件
            String[] projection = new String[]{"_id", "address", "body", "date", "read"};
            String sortOrder = "date DESC LIMIT 5";
            String selection = "read = 0"; // 只选择未读短信

            cursor = contentResolver.query(uri, projection, selection, null, sortOrder);
            if (cursor != null && cursor.moveToFirst()) {
                do {
                    long id = cursor.getLong(cursor.getColumnIndexOrThrow("_id"));
                    String body = cursor.getString(cursor.getColumnIndexOrThrow("body"));

                    // 2025-06-03 添加：验证短信内容有效性
                    if (id > lastSmsId && isValidSms(body)) {
                        lastSmsId = id;
                        String sender = cursor.getString(cursor.getColumnIndexOrThrow("address"));
                        long timestamp = cursor.getLong(cursor.getColumnIndexOrThrow("date"));

                        Log.d(TAG, "发现有效新短信 - ID: " + id + ", 发送者: " + sender);

                        // 转发短信
                        if (SMSReceiver.isServiceRunning()) {
                            logToMainActivity("通过ContentObserver发现新短信 - 发送者: " + sender);
                            logToMainActivity("短信内容: " + body);
                            forwardSmsToEmail(sender, body, timestamp);
                            hasNewSms = true;
                        }
                    }
                } while (cursor.moveToNext());
            }
        } catch (Exception e) {
            Log.e(TAG, "从URI检查短信时出错: " + uri + ", " + e.getMessage(), e);
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }

        return hasNewSms;
    }

    // 2025-06-03 添加：短信内容验证方法
    private boolean isValidSms(String body) {
        // 验证短信内容是否有效，避免处理空内容或系统短信
        return body != null && !body.trim().isEmpty();
    }

    private long getLatestSmsId() {
        Cursor cursor = null;
        try {
            Uri uri = Uri.parse("content://sms/inbox");
            String[] projection = new String[]{"_id"};
            String sortOrder = "date DESC LIMIT 1";

            cursor = contentResolver.query(uri, projection, null, null, sortOrder);
            if (cursor != null && cursor.moveToFirst()) {
                lastSmsId = cursor.getLong(cursor.getColumnIndexOrThrow("_id"));
                Log.d(TAG, "初始化最新短信ID: " + lastSmsId);
            }
        } catch (Exception e) {
            Log.e(TAG, "获取最新短信ID时出错: " + e.getMessage(), e);
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
        return lastSmsId;
    }

    private void logToMainActivity(String message) {
        MainActivity mainActivity = MainActivity.getInstance();
        if (mainActivity != null) {
            mainActivity.addLogEntry(message);
        }
    }

    private void forwardSmsToEmail(String sender, String messageBody, long timestamp) {
        try {
            // 格式化时间戳
            java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss", java.util.Locale.getDefault());
            String timeStr = sdf.format(new java.util.Date(timestamp));

            // 构建邮件主题和内容
            String subject = "短信转发 - 来自 " + sender;
            String content = "发送者: " + sender + "\n" +
                    "时间: " + timeStr + "\n" +
                    "内容: " + messageBody + "\n\n" +
                    "--- 此邮件由短信转发服务自动发送 ---";

            // 发送邮件
            EmailSender.sendEmail(subject, content, success -> {
                MainActivity mainActivity = MainActivity.getInstance();
                if (mainActivity != null) {
                    if (success) {
                        mainActivity.addLogEntry("短信已转发到邮箱");
                    } else {
                        mainActivity.addLogEntry("短信转发失败，请检查网络和邮箱配置");
                    }
                }
            });

            Log.d(TAG, "短信转发请求已发送");

        } catch (Exception e) {
            Log.e(TAG, "转发短信到邮箱时出错: " + e.getMessage(), e);
            MainActivity mainActivity = MainActivity.getInstance();
            if (mainActivity != null) {
                mainActivity.addLogEntry("转发短信到邮箱时出错: " + e.getMessage());
            }
        }
    }
}